package com.rh.bmw4s.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.rh.bmw4s.R;
import com.rh.bmw4s.bean.AddCarBean;
import com.rh.bmw4s.bean.EditCarInfoBean;
import com.rh.bmw4s.bean.EventInfo;
import com.rh.bmw4s.bean.FaDongJiBean;
import com.rh.bmw4s.bean.GoodsCategory;
import com.rh.bmw4s.bean.UpLoadImgBean;
import com.rh.bmw4s.comm.ConfigValue;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.utills.CheckUtil;
import com.rh.bmw4s.utills.DialogUtils;
import com.rh.bmw4s.utills.LogUtils;
import com.rh.bmw4s.utills.SPUtils;
import com.rh.bmw4s.utills.ToastUtils;
import com.rh.bmw4s.utills.glide.GlideImageLoader;
import com.rh.bmw4s.view.PicassoImageLoader;
import com.rh.bmw4s.view.fragdialog.SelectColorDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.SinglePicker;
import cn.qqtheme.framework.widget.WheelView;

/**
 * 添加车辆 编辑车辆
 */
public class AddCarActivity extends BaseActivity {

    @BindView(R.id.edit_addcar_name)
    EditText editName;
    @BindView(R.id.edit_addcar_phone)
    EditText editPhone;
    @BindView(R.id.tv_addcar_birthday)
    TextView tvBirthday;
    @BindView(R.id.img_addcar_no)
    ImageView imgNo;
    @BindView(R.id.ll_addcar_no)
    LinearLayout llNo;
    @BindView(R.id.img_addcar_yes)
    ImageView imgYes;
    @BindView(R.id.ll_addcar_yes)
    LinearLayout llYes;
    @BindView(R.id.tv_addcar_fadongji)
    TextView tvFadongji;
    @BindView(R.id.edit_addcar_xinghao)
    EditText editXinghao;
    @BindView(R.id.edit_addcar_chepai)
    EditText editChepai;
    @BindView(R.id.edit_addcar_chejiahao)
    EditText editChejiahao;
    @BindView(R.id.tv_addcar_shangpai)
    TextView tvShangpaiDate;
    //    @BindView(R.id.edit_addcar_color)
//    EditText editColor;
    @BindView(R.id.tv_addcar_commit)
    TextView tvCommit;
    @BindView(R.id.rel_addcar_birthday)
    RelativeLayout relBirthday;
    @BindView(R.id.rel_addcar_selectimg)
    RelativeLayout relSelectimg;
    @BindView(R.id.rel_addcar_fadongji)
    RelativeLayout relFadongji;
    @BindView(R.id.rel_addcar_shangpaiday)
    RelativeLayout relShangpaiday;
    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;

    private static final int IMAGE_PICKER = 202;
    @BindView(R.id.img_addcar_photo)
    ImageView imgPhoto;
    @BindView(R.id.tv_addcar_chejiahao)
    TextView tvChejiahao;
    @BindView(R.id.tv_chejiahao_must)
    TextView tvChejiahaoMust;
    @BindView(R.id.tv_addcar_color)
    TextView tvColor;
    private Gson gson;
    private GlideImageLoader imageLoader;
    private int isBaoMa = 1;
    List<GoodsCategory> dataFadongji = new ArrayList<>();
    private int anInt;
    private int enginId;  //发动机id
    private String imgPath = "";    //上传图片后，返回的地址
    private int mycarId;
    private int isEdit;  //1是编辑 0添加


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_car);
        ButterKnife.bind(this);

        gson = new Gson();
        imageLoader = new GlideImageLoader(AddCarActivity.this);
        anInt = SPUtils.getInstance().getInt(ConfigValue.userId);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mycarId = bundle.getInt("mycarid");
            isEdit = bundle.getInt("isedit");
        }

        initView();
        initPicker();
        getFaDongJi();

        if (isEdit == 1) {
            //重新编辑车辆,获取信息添加到相应位置
            DialogUtils.showProgressDlg(AddCarActivity.this, "正在加载......");
            OkGo.<String>post(Constant.EditCarInfo)
                    .tag(AddCarActivity.this)
                    .params("user_id", anInt)
                    .params("mycar_id", mycarId)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            DialogUtils.stopProgressDlg();
                            LogUtils.d("lll", response.body().toString());
                            EditCarInfoBean infoBean = gson.fromJson(response.body().toString(), EditCarInfoBean.class);
                            if (infoBean.getStatus() == Constant.SUCESS) {
                                EditCarInfoBean.DatasBean bean = infoBean.getDatas();
                                editName.setText(bean.getX_name());
                                editPhone.setText(bean.getTel());
                                tvBirthday.setText(bean.getBirthday());
                                if (bean.getIs_baoma() == 0) { //不是宝马
                                    tvChejiahao.setVisibility(View.VISIBLE);
                                    tvChejiahaoMust.setVisibility(View.GONE);
                                    imageLoader.display(imgNo, R.mipmap.icon_danxuan);
                                    imageLoader.display(imgYes, R.mipmap.icon_danxuan_no);
                                } else {
                                    tvChejiahao.setVisibility(View.GONE);
                                    tvChejiahaoMust.setVisibility(View.VISIBLE);
                                    imageLoader.display(imgYes, R.mipmap.icon_danxuan);
                                    imageLoader.display(imgNo, R.mipmap.icon_danxuan_no);
                                }
                                imgPath = bean.getLogo();
                                imageLoader.displayCircle(bean.getLogo(), imgPhoto);
                                enginId = bean.getId();
                                tvFadongji.setText(bean.getName()); //发动机缸数
                                editXinghao.setText(bean.getChexing());
                                editChepai.setText(bean.getChepai());
                                editChejiahao.setText(bean.getChejia());
                                tvShangpaiDate.setText(bean.getSpdate());
                                tvColor.setText(bean.getChecolor());

                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            DialogUtils.stopProgressDlg();
                            ToastUtils.toastForShort(AddCarActivity.this, "加载信息失败");
                        }
                    });

        }


        //车牌不能输入空格
        editChepai.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15), filter});
        //车架号输入大写字母加数字
        editChejiahao.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                editChejiahao.removeTextChangedListener(this);//解除文字改变事件
                editChejiahao.setText(charSequence.toString().toUpperCase());//转换
                editChejiahao.setSelection(charSequence.toString().length());//重新设置光标位置
                editChejiahao.addTextChangedListener(this);//重新绑
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


    }

    private InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            //返回null表示接收输入的字符,返回空字符串表示不接受输入的字符
            if (source.equals(" ")) {
                ToastUtils.toastForShort(AddCarActivity.this, "不能输入空格");
                return "";
            } else {
                return null;
            }
        }
    };


    /**
     * 获取发动机缸数
     */
    private void getFaDongJi() {
        OkGo.<String>get(Constant.FaDongJi)
                .tag(AddCarActivity.this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        FaDongJiBean faDongJiBean = gson.fromJson(response.body().toString(), FaDongJiBean.class);
                        if (faDongJiBean.getStatus() == Constant.SUCESS) {
                            List<FaDongJiBean.DatasBean> listFadong = faDongJiBean.getDatas();
                            for (int i = 0; i < listFadong.size(); i++) {
                                int fadongjiId = listFadong.get(i).getId();
                                String name = listFadong.get(i).getName();
                                dataFadongji.add(new GoodsCategory(fadongjiId, name));
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }


    private void initView() {
        titleLeftOneBtn.setVisibility(View.VISIBLE);

        if (isEdit == 0) {
            tvMiddleTitle.setText("添加车辆");
        } else {
            tvMiddleTitle.setText("编辑车辆");
        }
    }

    private void initPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setMultiMode(false);  //单选
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
    }

    @OnClick({R.id.title_left_one_btn, R.id.ll_addcar_no, R.id.ll_addcar_yes
            , R.id.tv_addcar_commit, R.id.rel_addcar_birthday, R.id.rel_addcar_selectimg,
            R.id.rel_addcar_fadongji, R.id.rel_addcar_shangpaiday, R.id.tv_addcar_color})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                finish();
                break;
            case R.id.ll_addcar_no:
                isBaoMa = 0;
                tvChejiahao.setVisibility(View.VISIBLE);
                tvChejiahaoMust.setVisibility(View.GONE);
                imageLoader.display(imgNo, R.mipmap.icon_danxuan);
                imageLoader.display(imgYes, R.mipmap.icon_danxuan_no);
                break;
            case R.id.ll_addcar_yes:
                isBaoMa = 1;
                tvChejiahao.setVisibility(View.GONE);
                tvChejiahaoMust.setVisibility(View.VISIBLE);
                imageLoader.display(imgYes, R.mipmap.icon_danxuan);
                imageLoader.display(imgNo, R.mipmap.icon_danxuan_no);
                break;
            case R.id.rel_addcar_birthday:
                final DatePicker picker = new DatePicker(this);
                picker.setCanceledOnTouchOutside(false);
                //设置滚轮项填充宽度，分割线最长
                picker.setUseWeight(true);
                picker.setRangeEnd(2017, 10, 16);
                picker.setRangeStart(1980, 1, 1);
                picker.setSelectedItem(2010, 1, 1);
                picker.setResetWhileWheel(false);
                picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        tvBirthday.setText(year + "-" + month + "-" + day);
                    }
                });
                picker.show();
                break;
            case R.id.rel_addcar_selectimg: //选择图片
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                break;
            case R.id.rel_addcar_fadongji:
                selectFaDongJi();
                break;
            case R.id.rel_addcar_shangpaiday:
                final DatePicker picker1 = new DatePicker(this);
                picker1.setCanceledOnTouchOutside(false);
                //设置滚轮项填充宽度，分割线最长
                picker1.setUseWeight(true);
                picker1.setRangeEnd(2017, 10, 16);
                picker1.setRangeStart(1980, 1, 1);
                picker1.setSelectedItem(2010, 1, 1);
                picker1.setResetWhileWheel(false);
                picker1.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        tvShangpaiDate.setText(year + "-" + month + "-" + day);
                    }
                });
                picker1.show();
                break;
            case R.id.tv_addcar_color:
                final SelectColorDialog selectColorDialog = new SelectColorDialog();
                selectColorDialog.setType(1);
                selectColorDialog.show(getFragmentManager(), "selectColorDialog");
                selectColorDialog.setSelectItemClickListener(new SelectColorDialog.OnSelectItemClickListener() {
                    @Override
                    public void pullSelect(String s) {
                        tvColor.setText(s);
                        selectColorDialog.dismiss();
                    }
                });
                break;
            case R.id.tv_addcar_commit:
                if (checkInfo()) {
                    beginCommit();
                }
                break;
        }
    }

    private String strName = "";
    private String strPhone = "";
    private String strBitthday = "";
    private String strFadongj = "";
    private String strXinghao = "";
    private String strChepai = "";
    private String strChejiahao = "";
    private String strShangPai = "";
    private String strColor = "";

    private PostRequest<String> request = null;

    /**
     * 开始提交
     */
    private void beginCommit() {
        //long timeStamp = TimeUtils.getTimeStamp(tvShangpaiDate.getText().toString()); //上牌时间戳
        DialogUtils.showProgressDlg(AddCarActivity.this, "正在提交......");

        if (isEdit == 0) {//添加车辆接口
            request = OkGo.<String>post(Constant.AddCarInfo);
        } else {//重新编辑车辆接口后，再次提交信息
            request = OkGo.<String>post(Constant.EditCarCommit)
                    .params("id", mycarId);
        }
        request.tag(AddCarActivity.this)
                .params("member_id", anInt)
                .params("x_name", strName)
                .params("tel", strPhone)
                .params("birthday", strBitthday)
                .params("is_baoma", isBaoMa)
                .params("chexing", strXinghao)
                .params("chepai", strChepai)
                .params("chejia", strChejiahao)
                .params("spdate", strShangPai)
                .params("engine", enginId)
                .params("logo", imgPath)
                .params("checolor", strColor)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        LogUtils.d("mmm", response.body().toString());
                        AddCarBean bean = gson.fromJson(response.body().toString(), AddCarBean.class);
                        ToastUtils.toastForShort(AddCarActivity.this, bean.getMsg());
                        if (bean.getStatus() == Constant.SUCESS) {
                            EventBus.getDefault().postSticky(new EventInfo(11));
                            finish();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(AddCarActivity.this, "添加失败");
                    }
                });


    }


    /**
     * 检查必填项是否填写
     */
    private boolean checkInfo() {
        strName = editName.getText().toString();
        strPhone = editPhone.getText().toString();
        strBitthday = tvBirthday.getText().toString();
        strFadongj = tvFadongji.getText().toString();
        strXinghao = editXinghao.getText().toString();       //车辆型号
        strChepai = editChepai.getText().toString();         //车牌
        strChejiahao = editChejiahao.getText().toString();         //车架号
        strShangPai = tvShangpaiDate.getText().toString();         //上牌日期
        strColor = tvColor.getText().toString();

        if (TextUtils.isEmpty(strName)) {
            ToastUtils.toastForShort(AddCarActivity.this, "姓名不能为空");
            return false;
        }
        if (!CheckUtil.isMobileNO(strPhone)) {
            ToastUtils.toastForShort(AddCarActivity.this, "手机号码错误");
            return false;
        }
        if (TextUtils.isEmpty(strBitthday)) {
            ToastUtils.toastForShort(AddCarActivity.this, "生日不能为空");
            return false;
        }
        if (TextUtils.isEmpty(imgPath)) {
            ToastUtils.toastForShort(AddCarActivity.this, "图片不能为空");
            return false;
        }
        if (TextUtils.isEmpty(strFadongj)) {
            ToastUtils.toastForShort(AddCarActivity.this, "发动机数不能为空");
            return false;
        }
        if (TextUtils.isEmpty(strXinghao)) {
            ToastUtils.toastForShort(AddCarActivity.this, "车辆型号不能为空");
            return false;
        }
        if (TextUtils.isEmpty(strChepai)) {
            ToastUtils.toastForShort(AddCarActivity.this, "车牌不能为空");
            return false;
        }
        if (isBaoMa == 1) {
            //是宝马的话，车架号必选
            if (TextUtils.isEmpty(strChejiahao)) {
                ToastUtils.toastForShort(AddCarActivity.this, "车架号不能为空");
                return false;
            } else if (strChejiahao.length() < 17) {
                ToastUtils.toastForShort(AddCarActivity.this, "车架号不能少于17位");
                return false;
            }
        }

        if (TextUtils.isEmpty(strShangPai)) {
            ToastUtils.toastForShort(AddCarActivity.this, "上牌日期不能为空");
            return false;
        }

        return true;
    }

    /**
     * 选择发动机
     */
    private void selectFaDongJi() {
        SinglePicker<GoodsCategory> picker = new SinglePicker<>(this, dataFadongji);
        picker.setCanceledOnTouchOutside(false);
        picker.setCycleDisable(false);
        picker.setLineSpaceMultiplier(3);
        picker.setOffset(2);
        picker.setDividerRatio(WheelView.DividerConfig.FILL);
        picker.setTextSize(16);
        picker.setTextPadding(10);

        picker.setOnItemPickListener(new SinglePicker.OnItemPickListener<GoodsCategory>() {

            @Override
            public void onItemPicked(int index, GoodsCategory item) {
                tvFadongji.setText(item.getName());
                enginId = item.getId();
            }
        });
        picker.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem item = images.get(0);
                upLoadImg(item.path);
            } else {
                ToastUtils.toastForShort(AddCarActivity.this, "图片未获取");
            }
        }
    }

    private void upLoadImg(final String selectPath) {
        DialogUtils.showProgressDlg(AddCarActivity.this, "正在上传....");
        OkGo.<String>post(Constant.UpLoadImg)
                .tag(AddCarActivity.this)
                .params("logo", new File(selectPath))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        LogUtils.d("fff", selectPath);
                        LogUtils.d("fff", response.body().toString());
                        UpLoadImgBean imgBean = gson.fromJson(response.body().toString(), UpLoadImgBean.class);
                        if (imgBean.getStatus() == Constant.SUCESS) {
                            imageLoader.displayCircle(selectPath, imgPhoto);

                            imgPath = imgBean.getDatas();
                            ToastUtils.toastForShort(AddCarActivity.this, "上传图片成功");
                        } else {

                            ToastUtils.toastForShort(AddCarActivity.this, "上传失败");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(AddCarActivity.this, "上传失败");

                    }
                });
    }


}
